<?php

/**
 * @version $Id$
 * @package
 * @author Alexander Anokhin <ava@vaz.ru>
 */

class Person extends Zend_Db_Table_Row {
	
	public function findDocuments($type = null)
	{
		
	   $select = null;

	   if(!is_null($type))
	   {
         /**
	      * @ugly how to not hardcode an alias name? 
	      */
	      $select = $this->getTable()->select()
              			->where('"m".type = ?', $type);
	   }
	   
	   echo $select;
		
	   return $this->findDocumentsViaPersonDocsByPerson($select);
	   

	}
	
	public function findActiveAccount() {
		$sql = "
				SELECT 'i'.*, 'm'.* FROM 'person_acc' AS 'i'
			 	INNER JOIN 'account' AS 'm' ON 'i'.'acc_key' = 'm'.'acc_key' 
			 	WHERE 'i'.'person_id' = {$this->person_id}
			 		and 'i'.start < '".Util::date()."' and 'i'.stop_ > '".Util::date()."'
			 ";
			 
		return $this->_getAccountsRowSetBySqlQuery($sql);
	}
	
	private function _getAccountsRowSetBySqlQuery($sql) {
		$matchTable =  new Accounts(array("db"=>$this->getTable()->getAdapter()));
        $config = array(
            'table'    => $matchTable,
            'data'     => $this->getTable()->getAdapter()->query($sql)->fetchAll(Zend_Db::FETCH_ASSOC),
            'rowClass' => $matchTable->getRowClass(),
            'readOnly' => false,
            'stored'   => true
        );

        $rowsetClass = $matchTable->getRowsetClass();
        try {
            @Zend_Loader::loadClass($rowsetClass);
        } catch (Zend_Exception $e) {
            require_once 'Zend/Db/Table/Row/Exception.php';
            throw new Zend_Db_Table_Row_Exception($e->getMessage());
        }
        return new $rowsetClass($config);
	}

	public function createDocument($type)
	{
		   $docs = new Documents;
		   $docs->setRowClass(Document_Factory::getDocumentClass($type));
		   $doc = $docs->createRow(array('type'=>$type));
		   
		   $doc->assignTo($this);
		   return $doc;
	}
	
	public function findDocument($id)
	{
		foreach($this->findDocuments() as $document)
			if($document->doc_id == $id)
				return $document;

		throw new Assignee_Exception_NotFound("No such document [$id]");
	}
	
	public function getTitle()
	{
		return Util::iconvStorageToApp(		    $this->last_name 
										. ' ' . $this->first_name[0]
										. '. ' . $this->midle_name[0]
										. '.'
										);
	}
	
	public function getId()
	{
		return $this->person_id;
	}
	
	public function getAssignationId()
	{
		return $this->person_id;
	}
	
	public function deleteDocument($id)
	{
		$this->findDocument($id)->delete();
	}
	
	
	
}
